from django.contrib import admin
from .models import User, PlayerStatus, PlayerStuff, PlayerEquipment
from import_export.admin import ImportExportMixin


class UserAdmin(ImportExportMixin, admin.ModelAdmin):
    list_display = ('username', 'nick_name', 'phone')
    list_display_links = ('username',)
    search_fields = ['username', 'nick_name']
    readonly_fields = ['last_login', 'date_joined']

    # 用于在创建用户时使用
    add_fieldsets = (
        ('用户信息', {'fields': ('username', 'password1', 'password2', 'phone', 'email')}),
        ('角色信息', {'fields': ('nick_name', 'avatar')}),
        ('登录记录', {'fields': ('last_login', 'date_joined')}),
    )

    # 用于在编辑用户时使用
    fieldsets = (
        ('用户信息', {'fields': ('username', 'password', 'phone', 'email')}),
        ('角色信息', {'fields': ('nick_name', 'avatar')}),
        ('登录记录', {'fields': ('last_login', 'date_joined')}),
    )

    def save_model(self, request, obj, form, change):
        obj.save()
        player_status, created = PlayerStatus.objects.update_or_create(player=obj)
        player_status.save()


class PlayerStatusAdmin(ImportExportMixin, admin.ModelAdmin):
    def get_player_nickname(self, obj):
        return obj.player.nick_name

    get_player_nickname.short_description = '玩家昵称'
    list_display = ('get_player_nickname', 'level', 'location')
    list_display_links = ('get_player_nickname',)
    search_fields = ['get_player_nickname']
    readonly_fields = ['max_experience', 'max_attack', 'location']

    # 用于在创建用户时使用
    add_fieldsets = (
        ('角色信息', {'fields': ('player', 'level', 'location')}),
        ('角色进度', {'fields': ('experience', 'max_experience')}),
        ('角色属性', {'fields': ('health', 'max_health', 'min_attack', 'max_attack', 'defense', 'agility', 'momentum')}),
    )

    # 用于在编辑用户时使用
    fieldsets = (
        ('角色信息', {'fields': ('player', 'level', 'location')}),
        ('角色进度', {'fields': ('experience', 'max_experience')}),
        ('角色属性', {'fields': ('health', 'max_health', 'min_attack', 'max_attack', 'defense', 'agility', 'momentum')}),
    )

    def save_model(self, request, obj, form, change):
        obj.save()
        player_status, created = PlayerStatus.objects.update_or_create(player=obj)
        player_status.save()


admin.site.register(User, UserAdmin)
admin.site.register(PlayerStatus, PlayerStatusAdmin)
admin.site.register(PlayerStuff)
admin.site.register(PlayerEquipment)
